﻿using Basic.FormCollect;
using Basic.FormModel.DB;
using Basic.FormRemoteModel;
using Basic.FormService.Interface;
using WeDonekRpc.Helper;

namespace Basic.FormService.Extend
{
    internal class FormEnableService : IFormEnableService
    {
        private readonly ICustomFormCollect _Form;
        private readonly ICustomTableCollect _Table;
        private readonly ITableColumnCollect _Column;
        private readonly IPhysicalTableCollect _PhyTable;
        private readonly IFormViewCollect _FormView;
        private readonly IPhyTableCreateService _PhyQuery;
        public FormEnableService ( ICustomFormCollect form,
            ICustomTableCollect table,
            IPhysicalTableCollect phy,
            IFormViewCollect formView,
            IPhyTableCreateService phyQuery,
            ITableColumnCollect column )
        {
            this._FormView = formView;
            this._PhyQuery = phyQuery;
            this._PhyTable = phy;
            this._Form = form;
            this._Table = table;
            this._Column = column;
        }

        public bool Enable ( long id )
        {
            DBCustomForm form = this._Form.Get(id);
            if ( form.FormType == FormType.物理表单 )
            {
                return this._EnablePhy(form);
            }
            else if ( form.FormType == FormType.视图 )
            {
                if ( !this._FormView.CheckIsGenerate(id) )
                {
                    throw new ErrorException("form.view.no.generate");
                }
            }
            else if ( form.FormType == FormType.自定义表单 )
            {
                long[] tableId = this._Table.GetsByFormId<long>(id, a => a.Id);
                if ( tableId.IsNull() )
                {
                    throw new ErrorException("form.table.null");
                }
                tableId = this._Column.CheckIsNull(id, tableId);
                if ( !tableId.IsNull() )
                {
                    throw new ErrorException("form.table.column.null");
                }
            }
            else if ( this._PhyTable.CheckIsNull(id) )
            {
                throw new ErrorException("form.physical.table.null");
            }
            return this._Form.SetStatus(form, FormStatus.启用);
        }
        private bool _EnablePhy ( DBCustomForm form )
        {
            if ( form.FormStatus == FormStatus.启用 )
            {
                return false;
            }
            else if ( form.FormStatus == FormStatus.起草 )
            {
                this._PhyQuery.Check(form.Id);
                if ( this._Form.SetStatus(form, FormStatus.启用) )
                {
                    this._PhyQuery.Create();
                    return true;
                }
                return false;
            }
            else
            {
                return this._Form.SetStatus(form, FormStatus.启用);
            }
        }
    }
}
